#-*- coding:utf-8 -*-
"""
" ip2region python seacher client module
"
" Autho: koma<komazhang@foxmail.com>
" Date : 2015-11-06
"""
import struct, sys, os, time
import traceback
from platform import python_version
import urllib
from ip2Region import Ip2Region

def testSearch():
    """
    " ip2region test function
    """
    argLen     = len(sys.argv)
    version    = python_version()
    algorithms = ["binary", "b-tree", "memory"]

    dbFile = "/opt/third-party/ip2region/ip2region.db"

    try:
        algorithms.index(algorithm)
    except Exception as e:
        algorithm = "b-tree"

    searcher = Ip2Region(dbFile)

    line = sys.argv[1]

    line = line.strip()

    if line == "":
        print("ip is empty- - - -")
        return


    if not searcher.isip(line):
        print("not is ip - - - -")
        return

    try:
        sTime = time.time()*1000
        if algorithm == "binary":
            data = searcher.binarySearch(line)
        elif algorithm == "memory":
            data = searcher.memorySearch(line)
        else:
            data = searcher.btreeSearch(line)
        eTime = time.time()*1000
        #print("%s|%s in %5f millseconds" % (data["city_id"], data["region"].decode('utf-8'), eTime - sTime))
        res=data["region"].decode('utf-8',"ignore")
        ips= res.split('|')
        county=ips[0]
        
        res= "%s %s %s %s" % (ips[0].replace("0","-"),ips[2].replace("0","-"),ips[3].replace("0","-"),ips[4].replace("0","-"))
        res= res.encode('utf-8')
        #print(type(res))
        print(res)
    except Exception as e:
        print(e)

    searcher.close()

if __name__ == "__main__":
    testSearch()
